#pragma once

#include <iostream>
#include <string>
#include <functional>
#include "Reactor.hpp"

class Connection;
class Reactor;

using func_t = std::function<void(Connection*)>;

class Connection
{
public:
    Connection(int sockfd, uint32_t events, Reactor* svrFrom): _sockfd(sockfd), _events(events), _svrFrom(svrFrom)
    {}

    void setCallBacks(func_t read, func_t write, func_t except)
    {
        _read = read;
        _write = write;
        _except = except;
    }

    int getSockFd()
    {
        return _sockfd;
    }

    uint32_t getEvents()
    {
        return _events;
    }

    void setEvents(uint32_t events)
    {
        _events = events;
    }

    std::string getClientIp()
    {
        return _clientIp;
    }

    void setClientIp(std::string clientIp)
    {
        _clientIp = clientIp;
    }

    uint16_t getClientPort()
    {
        return _clientPort;
    }

    void setClientPort(uint16_t clientPort)
    {
        _clientPort = clientPort;
    }

    std::string& getInBuffer()
    {
        return _inBuffer; //引用返回
    }

    void appendInBuffer(std::string buffer)
    {
        _inBuffer += buffer;
    }

    std::string& getOutBuffer()
    {
        return _outBuffer; //引用返回
    }

    void appendOutBuffer(std::string buffer)
    {
        _outBuffer += buffer;
    }

    bool isOutBufferEmpty()
    {
        return _outBuffer.empty();
    }

    void closeFd()
    {
        ::close(_sockfd);
    }

    ~Connection()
    {}
public:
    // 回调
    func_t _read;
    func_t _write;
    func_t _except;

    // 回指
    Reactor* _svrFrom;
private:
    // 描述符及其缓冲区
    int _sockfd;
    std::string _inBuffer; //接受缓冲区
    std::string _outBuffer; //发送缓冲区

    // 关心的事件
    uint32_t _events;

    // 客户端信息
    std::string _clientIp;
    uint16_t _clientPort;
};